package com.zmn.oms.task.job.perf;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.spring.tasktracker.JobRunnerItem;
import com.github.ltsopensource.spring.tasktracker.LTS;
import com.github.ltsopensource.tasktracker.Result;
import com.zmn.common.dto.ResultDTO;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.oms.business.interfaces.perf.PerfMasterCategBService;
import com.zmn.oms.manager.utils.TaskConsts;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

/**
 * 类描述：分类绩效任务
 *
 * @author hankangshuai
 * @date 2019/09/30 11:08
 */
@LTS
@Slf4j
public class PerfMasterCategJob {

    @Resource
    TaskManager taskManager;

    @Resource
    PerfMasterCategBService perfMasterCategBService;

    /**
     * 工程师绩效分类绩效
     * 每天晚上2点统计
     */
    @PostConstruct
    void init() {
        Job job = new Job();
        job.setTaskId(TaskConsts.TASK_ID_PERF_MASTER_CATEG);
        job.setParam(TaskManager.SHARD_FIELD, TaskConsts.TASK_ID_PERF_MASTER_CATEG);
        job.setCronExpression("0 0 02 * * ?");
        job.setReplaceOnExist(true);
        ResultDTO result = taskManager.submitTask(job);
        if (!result.getStatusBool()) {
            log.error("#perf_master# job submit fail...");
        }
    }

    /**
     * 运行贴花明细统计
     * 1、统计当月的
     * 2、如果当前时间是1-5号则需要统计上个月
     */
    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_PERF_MASTER_CATEG)
    public Result run(Job job) {
        String yearMonth = job.getParam("yearMonth");
        YearMonth syncMonth;
        if (StringUtil.isNotBlank(yearMonth)) {
            syncMonth = YearMonth.parse(yearMonth, DateTimeFormatter.ofPattern("yyyyMM"));
        } else {
            syncMonth = YearMonth.now();
        }
        perfMasterCategBService.sync(syncMonth);
        // 如果是1-5号额外统计上个月
        if (LocalDate.now().getDayOfMonth() < 6) {
            YearMonth lastMonth = syncMonth.plusMonths(-1);
            perfMasterCategBService.sync(lastMonth);
        }
        return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
    }
}
